<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="控制卡号" prop="dsId">
        <el-input v-model="queryParams.dsId" placeholder="请输入控制卡号" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd" v-hasPermi="['iot:hgdisplay:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:hgdisplay:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:hgdisplay:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button id="openbtn" type="success" :plain="selectedRows.length === 0" size="mini" :disabled="selectedRows.length === 0" @click="handleTurnOn(selectedRows)">
          <i class="el-icon-video-play" style="font-size: 1.3em; margin-right: 6px;"/>开启</el-button>
<el-button id="closebtn" type="danger" :plain="selectedRows.length === 0" size="mini" :disabled="selectedRows.length === 0" @click="handleTurnOff(selectedRows)">
          <i class="el-icon-video-pause" style="font-size: 1.3em; margin-right: 6px;"/>关闭</el-button>
      </el-col>
      <el-col :span="2.1" style="margin-left:5px;display:flex;align-items:center;">
          <span style="font-size:12px;margin-right:5px;">调亮度</span>
            <el-select v-model="sldLightLvl" :disabled="selectedRows.length===0" size="mini" style="width:100px;" @change="updtLevel">
              <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
      </el-col>
      <el-col :span="2.1" style="margin-left:5px;display:flex;align-items:center;">
          <span style="font-size:12px;margin-right:5px;">调音量</span>
            <el-select v-model="sldVolumeLvl" :disabled="selectedRows.length===0" size="mini" style="width:100px;" @change="updtVolume">
              <el-option v-for="item in volumeOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
      </el-col>
    <el-col :span="1.5">
    <el-button type="primary" plain icon="el-icon-time" size="small" @click="openDialog"
      :disabled="selectedRows.length===0" :class="{'plain-button':selectedRows.length===0}">定时</el-button></el-col>
    <el-col :span="1.5">
    <el-button type="warning" plain icon="el-icon-upload" size="small" @click="sendDialog"
      :disabled="selectedRows.length===0" :class="{'plain-button':selectedRows.length===0}">节目发送</el-button></el-col>
    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/></el-row>
<el-table v-loading="loading" :data="hgdisplayList" style="width:100%" border @selection-change="handleSelectionChange" fit @mouseenter.native="handleTableMouseEnter" @mouseleave.native="handleTableMouseLeave" ref="dataTable" class="hover-operate-table">
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column label="客户" align="center" prop="nickName" width="155" show-overflow-tooltip/>
      <el-table-column label="项目" align="center" prop="projectname" width="155" show-overflow-tooltip/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="控制卡号" align="center" prop="dsId" width="117" show-overflow-tooltip/>
      <el-table-column label="灯杆序号" align="center" prop="boxNo" show-overflow-tooltip/>
      <el-table-column label="灯杆名称" align="center" prop="lightName" width="125" show-overflow-tooltip/>
      <el-table-column label="在线状态" align="center" width="86">
        <template slot-scope="scope">
          <div class="status-container"><img :src="getStateImags(scope.row.state)" alt="在线状态" style="width:22px;height:22px;"/></div>
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center">
        <template slot-scope="scope">
          <div class="status-container"><img :src="getStatusImage(scope.row.dsStatus)" alt="工作状态" style="width:22px;height:22px;"/></div>
        </template>
      </el-table-column>
      <el-table-column label="卡类型" prop="dsType" align="center" width="80">
        <template slot-scope="scope"><dict-tag :options="dict.type.iot_ds_type" :value="scope.row.dsType"/></template>
      </el-table-column>
      <el-table-column label="亮度" prop="dsAdjustLevel" align="center" width="80">
        <template slot-scope="scope"><dict-tag :options="dict.type.iot_ds_level" :value="scope.row.dsAdjustLevel"/></template>
      </el-table-column>
      <el-table-column label="音量" prop="dsVolumeLevel" align="center" width="80">
        <template slot-scope="scope"><dict-tag :options="dict.type.iot_ds_volume" :value="scope.row.dsVolumeLevel"/></template>
      </el-table-column>
      <el-table-column label="定时策略" align="center" prop="content">
        <template slot-scope="scope">
          <img v-if="cronBoxNoList.includes(scope.row.dsId)" :src="require(`@/assets/bigScreen/img/localStrategy.png`)"
            style="width:18px;height:auto;cursor:pointer;" @click="openStrategyDialog(scope.row)" v-hasPermi="['iot:cron:edit']"/>
  <span v-else style="color:#f56c6c;font-weight:bold;background-color:#fff4f4;padding:2px 6px;border-radius:4px;font-size:14px;">未定时</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="156">
        <template slot-scope="scope">{{scope.row.createTime}}</template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="156">
        <template slot-scope="scope">{{scope.row.updateTime||'未更新'}}</template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" width="190" :class-name="showOperateColumn?'operate-column show':'operate-column'">
        <template slot-scope="scope">
  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:hgdisplay:edit']">修改</el-button>
  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:hgdisplay:remove']">删除</el-button>
  <el-button size="mini" type="text" icon="el-icon-message" @click="operateUp(scope.row)" v-hasPermi="['iot:log:list']">操作记录</el-button>
        </template>
      </el-table-column>
    </el-table>
<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes" @pagination="getList"/>
<display-uusser ref="displayy"/>
<display-logger ref="logger"/>
<el-dialog title="定时设置" :visible.sync="dialogVisible" width="30%">
<el-form :model="form">
<el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略1</span></el-row>
  <el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.startTime" placeholder="开启时间" field="startTime"/></el-form-item></el-col>
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.endTime" placeholder="关闭时间" field="endTime"/></el-form-item></el-col></el-row>
  <div>
    <el-select v-model="form.lightAdjustLevel" placeholder="调光等级" class="custom-select move-select">
      <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select></div>
<el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略2</span></el-row>
  <el-row :gutter="20" style="margin-left: 50px; margin-top:-26px;">
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.startTimeTwo" field="startTimeTwo" placeholder="开启时间"/></el-form-item></el-col>
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.endTimeTwo" field="endTimeTwo" placeholder="关闭时间"/></el-form-item></el-col></el-row>
  <div>
    <el-select v-model="form.lightAdjustLevelTwo" placeholder="调光等级" class="custom-select move-select">
      <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select></div>
<el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略3</span></el-row>
  <el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.startTimeThree" field="startTimeThree" placeholder="开启时间"/></el-form-item></el-col>
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.endTimeThree" field="endTimeThree" placeholder="关闭时间"/></el-form-item></el-col></el-row>
  <div>
    <el-select v-model="form.lightAdjustLevelThree" placeholder="调光等级" class="custom-select move-select">
      <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select></div>
<el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略4</span></el-row>
  <el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.startTimeFour" field="startTimeFour" placeholder="开启时间"/></el-form-item></el-col>
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.endTimeFour" field="endTimeFour" placeholder="关闭时间"/></el-form-item></el-col></el-row>
  <div>
    <el-select v-model="form.lightAdjustLevelFour" placeholder="调光等级" class="custom-select move-select">
      <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select></div>
<el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略5</span></el-row>
  <el-row :gutter="20" style="margin-left:50px;margin-top:-26px;">
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.startTimeFive" field="startTimeFive" placeholder="开启时间"/></el-form-item></el-col>
  <el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
  <time-picker v-model="form.endTimeFive" field="endTimeFive" placeholder="关闭时间"/></el-form-item></el-col></el-row>
  <div>
    <el-select v-model="form.lightAdjustLevelFive" placeholder="调光等级" class="custom-select move-select">
      <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select></div>
</el-form>
<span slot="footer" class="dialog-footer">
  <el-button @click="dialogVisible=false">取 消</el-button>
  <el-button type="primary" @click="handleSubmitForStrategys">确 定</el-button></span>
</el-dialog>
<el-dialog title="定时策略详情" :visible.sync="dialogVisibleForStrategy" width="30%">
  <el-form ref="form" :model="form" label-width="58px">
          <el-form-item label="控制卡:" prop="boxNo"><span style="font-size:16px;">{{this.form.boxNo}}</span></el-form-item>
          <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略1</span></el-row>
          <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTime" field="startTime" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTime" field="endTime" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
          <div>
            <el-select v-model="form.lightAdjustLevel" placeholder="调光等级" class="custom-select move-select">
              <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select>
          </div>
          <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略2</span></el-row>
          <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeTwo" field="startTimeTwo" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeTwo" field="endTimeTwo" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
          <div>
            <el-select v-model="form.lightAdjustLevelTwo" placeholder="调光等级" class="custom-select move-select">
              <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select>
          </div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略3</span></el-row>
        <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeThree" field="startTimeThree" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeThree" field="endTimeThree" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
        <div>
          <el-select v-model="form.lightAdjustLevelThree" placeholder="调光等级" class="custom-select move-select">
            <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select>
        </div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略4</span></el-row>
        <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeFour" field="startTimeFour" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeFour" field="endTimeFour" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
        <div>
          <el-select v-model="form.lightAdjustLevelFour" placeholder="调光等级" class="custom-select move-select">
            <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select>
        </div>
        <el-row :gutter="30" style="margin-left:3px;"><span style="font-size:16px;color:#4169E1;">策略5</span></el-row>
        <el-row :gutter="10" style="margin-left:-3px;margin-top:-26px;">
<el-col :span="10"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.startTimeFive" field="startTimeFive" placeholder="开启时间" @change="handleEndTimeChange"/></el-form-item></el-col>
<el-col :span="12"><el-form-item style="border:1px solid #dcdfe6;border-radius:4px;padding:1px;">
<time-picker v-model="form.endTimeFive" field="endTimeFive" placeholder="关闭时间" @change="handleEndTimeChange"/></el-form-item></el-col></el-row>
        <div>
          <el-select v-model="form.lightAdjustLevelFive" placeholder="调光等级" class="custom-select move-select">
            <el-option v-for="item in dsLevelOptions" :key="item.value" :label="item.label" :value="item.value"/></el-select>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
<el-button @click="dialogVisibleForStrategy=false">取 消</el-button><el-button type="primary" @click="handleSubmitForStrategy">确 定</el-button>
      </span>
    </el-dialog>
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="客户名称" prop="customerId">
      <el-select v-model="form.customerId" placeholder="请选择客户名称" filterable style="width:100%" @change="handleNicknameChange">
        <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
      </el-select>
    </el-form-item>
    <el-form-item label="项目名称" prop="projectId">
      <el-select v-model="form.projectId" placeholder="请选择项目名称" filterable style="width:100%" @change="handleProjectnameChange">
        <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
      </el-select>
    </el-form-item>
    <el-form-item label="卡类型" prop="dsType">
      <el-select v-model="form.dsType" placeholder="请选择卡类型" filterable style="width:100%">
        <el-option v-for="dict in dict.type.iot_ds_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
      </el-select>
    </el-form-item>
    <el-form-item label="控制卡号" prop="dsId"><el-input v-model="form.dsId" placeholder="请输入控制卡号"/></el-form-item>
    <el-form-item label="灯杆序号" prop="boxNo"><el-input v-model="form.boxNo" placeholder="请输入灯杆序号"/></el-form-item>
    <el-form-item label="灯杆名称" prop="lightName"><el-input v-model="form.lightName" placeholder="请输入灯杆名称"/></el-form-item>
    <el-form-item label="备注" prop="remark"><el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/></el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer"><el-button type="primary" @click="submitForm">确 定</el-button><el-button @click="cancel">取 消</el-button></div>
</el-dialog>
</div>
</template>
<script>
import TimePicker from '../hgbox/TimePicker.vue';
import { addCron, listCron, updateCron, updateCronBoxNo } from '@/api/iot/fahgboxcron'
import { listHgdisplay, getHgdisplay, delHgdisplay, addHgdisplay, updateHgdisplay } from "@/api/iot/hgdisplay";
import Template from '@/views/iot/template/index.vue'
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'
import request from '@/utils/request'
import displayUusser from "./displayItem"
import displayLogger from "./dislogger"
export default {
  dicts:['iot_ds_type','iot_ds_level','iot_ds_volume'],
  name:"Hgdisplay",
  components:{Template,displayUusser,TimePicker,displayLogger},
  data() {
    return {
      showOperateColumn: false,
      dialogVisibleForStrategy: false,
      pollInterval: null, // 轮询定时器
      ssss : '',
      dialogVisible: false,
      pageSizes: [10,20,30,50],
      sldLightLvl: '',
      sldVolumeLvl: '',
      cronBoxNoList: [],
      cronList: [],
      selectedUserName: null,
      options: [],
      projectnameOptions: [],
      selectedRows: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      hgdisplayList: [],
      title: "",
      open: false,
      dsLevelOptions: [
        { label: '10%', value: '26' },
        { label: '20%', value: '51' },
        { label: '30%', value: '77' },
        { label: '40%', value: '102' },
        { label: '50%', value: '128' },
        { label: '60%', value: '153' },
        { label: '70%', value: '179' },
        { label: '80%', value: '204' },
        { label: '90%', value: '230' },
        { label: '100%', value: '255' }
      ],
      volumeOptions: [
        { label: '0%', value: 0 },
        { label: '20%', value: 3 },
        { label: '40%', value: 6 },
        { label: '60%', value: 9 },
        { label: '80%', value: 12 },
        { label: '100%', value: 15 }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        customerId: null,
        dsType: null,
        dsId: null,
        dsStatus: null,
        boxNo: null,
        lightName: null,
        projectId: null,
        lng: null,
        lat: null,
        state: null,
        deleteBy: null,
        deleteTime: null,
        dsAdjustLevel: null,
        dsError: null,
        signalt: null,
        mlux: null,
        soundDecibelValue: null,
        pm10: null,
        pm25: null,
        humidity: null,
        temperature: null
      },
      form: {},
      rules: {
        customerId: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        projectId: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        dsType: [{ required: true, message: "卡类型不能为空", trigger: "change" }],
        dsId: [{ required: true, message: "控制卡号不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
    this.fetchCronBoxNoList();
    this.startPolling(); // 开始轮询
  },
  beforeDestroy() {
    clearInterval(this.pollInterval);
  },
  methods: {
    handleEndTimeChange(field) {
      this.modifiedForm[field] = true;
      console.log('field:', field);
    },
    operateUp(row) {
      this.reset();
      this.$refs.logger.show(row.dsId);
    },
    handleTableMouseEnter(event) {
      const tableEl = this.$refs.dataTable.$el;
      const rect = tableEl.getBoundingClientRect();
      if (event.clientX > rect.right - 100) {
        this.showOperateColumn = true;
      }
    },
    handleTableMouseLeave() {this.showOperateColumn = false;},
    handleSubmitForStrategy() {
      const updatedCronData = [];
      const parseValue = (value) => {
        if (typeof value === 'string') {
          return parseInt(value);
        }
        return value;
      };
      if (this.modifiedForm.startTime) {updatedCronData.push({ startTime: this.form.startTime });}
      if (this.modifiedForm.endTime) {updatedCronData.push({ endTime: this.form.endTime });}
      if (this.modifiedForm.startTimeTwo) {updatedCronData.push({ startTimeTwo: this.form.startTimeTwo });}
      if (this.modifiedForm.endTimeTwo) {updatedCronData.push({ endTimeTwo: this.form.endTimeTwo });}
      if (this.modifiedForm.startTimeThree) {updatedCronData.push({ startTimeThree: this.form.startTimeThree });}
      if (this.modifiedForm.endTimeThree) {updatedCronData.push({ endTimeThree: this.form.endTimeThree });}
      if (this.modifiedForm.startTimeFour) {updatedCronData.push({ startTimeFour: this.form.startTimeFour });}
      if (this.modifiedForm.endTimeFour) {updatedCronData.push({ endTimeFour: this.form.endTimeFour });}
      if (this.modifiedForm.startTimeFive) {updatedCronData.push({ startTimeFive: this.form.startTimeFive });}
      if (this.modifiedForm.endTimeFive) {updatedCronData.push({ endTimeFive: this.form.endTimeFive });}
      if (this.modifiedForm.lightStatus) {updatedCronData.push({ lightStatus: this.form.lightStatus });}
      if (this.modifiedForm.lightAdjustLevel) {updatedCronData.push({ lightAdjustLevel: parseValue(this.form.lightAdjustLevel) });}
      if (this.modifiedForm.lightStatusTwo) {updatedCronData.push({ lightStatusTwo: this.form.lightStatusTwo });}
      if (this.modifiedForm.lightAdjustLevelTwo) {updatedCronData.push({lightAdjustLevelTwo:parseValue(this.form.lightAdjustLevelTwo)});}
      if (this.modifiedForm.lightStatusThree) {updatedCronData.push({ lightStatusThree: this.form.lightStatusThree });}
      if(this.modifiedForm.lightAdjustLevelThree){updatedCronData.push({lightAdjustLevelThree:parseValue(this.form.lightAdjustLevelThree)});}
      if(this.modifiedForm.lightStatusFour) {updatedCronData.push({ lightStatusFour: this.form.lightStatusFour });}
      if(this.modifiedForm.lightAdjustLevelFour){updatedCronData.push({lightAdjustLevelFour:parseValue(this.form.lightAdjustLevelFour)});}
      if(this.modifiedForm.lightStatusFive){updatedCronData.push({lightStatusFive:this.form.lightStatusFive});}
      if(this.modifiedForm.lightAdjustLevelFive){updatedCronData.push({lightAdjustLevelFive:parseValue(this.form.lightAdjustLevelFive)});}
      const updatedCron = {
        id: this.form.id,
        boxNo: this.form.boxNo,
        provideType: this.form.provideType,
        ...updatedCronData.reduce((acc,curr)=>({...acc,...curr}),{})
      };
      console.log('updatedCron:', updatedCron);
      updateCron(updatedCron).then(response => {
          this.$modal.msgSuccess("定时策略更新成功");
          this.dialogVisibleForStrategy = false;
        }).catch(error => {
          console.error('error:', error);
          this.$modal.msgError("操作失败: 请求错误");
        });
    },
    openStrategyDialog(row) {
      listCron({ boxNo: row.dsId }).then(response => {
          if (!response || typeof response !== 'object' || !Array.isArray(response.rows)) {
            console.error('response:', response);
            this.$message.error('响应格式不正确');
            return;
          }
          const cron = response.rows[0] || {};
          this.form = {
            startTime: cron.startTime,
            endTime: cron.endTime,
            boxNo: cron.boxNo,
            provideType: cron.provideType,
            id: row.id,
            startTimeTwo: cron.startTimeTwo,
            startTimeThree: cron.startTimeThree,
            startTimeFour: cron.startTimeFour,
            startTimeFive: cron.startTimeFive,
            endTimeTwo: cron.endTimeTwo,
            endTimeThree: cron.endTimeThree,
            endTimeFour: cron.endTimeFour,
            endTimeFive: cron.endTimeFive,
            lightStatus: cron.lightStatus,
            lightAdjustLevel : cron.lightAdjustLevel,
            lightStatusTwo: cron.lightStatusTwo,
            lightAdjustLevelTwo : cron.lightAdjustLevelTwo,
            lightStatusThree: cron.lightStatusThree,
            lightAdjustLevelThree : cron.lightAdjustLevelThree,
            lightStatusFour: cron.lightStatusFour,
            lightAdjustLevelFour : cron.lightAdjustLevelFour,
            lightStatusFive: cron.lightStatusFive,
            lightAdjustLevelFive : cron.lightAdjustLevelFive,
          };
          this.modifiedForm = {
            startTime: false,
            endTime: false,
            startTimeTwo: false,
            endTimeTwo: false,
            startTimeThree: false,
            endTimeThree: false,
            startTimeFour: false,
            endTimeFour: false,
            startTimeFive: false,
            endTimeFive: false,
            lightStatus:false,
            lightAdjustLevel: false,
            lightStatusTwo:false,
            lightAdjustLevelTwo: false,
            lightStatusThree:false,
            lightAdjustLevelThree: false,
            lightStatusFour:false,
            lightAdjustLevelFour: false,
            lightStatusFive:false,
            lightAdjustLevelFive: false,
          };
          this.dialogVisibleForStrategy = true;}).catch(error => {
          console.error('error:', error);
          this.$message.error('获取定时任务详情失败');});},
    fetchCronBoxNoList() {
      this.loading = true;
      listCron(this.queryParams).then(response => {
        this.cronList = response.rows;
        this.cronBoxNoList = this.cronList.map(item => item.boxNo);
        console.log('cronBoxNoList:', this.cronBoxNoList);
        this.loading = false;
      }).catch(error => {
        console.error("error:", error);
        this.loading = false;
      });
    },
    startPolling() {// 每10分钟秒轮询一次数据
      this.pollInterval = setInterval(this.getList, 600000);},
    checkDeviceHasCron(boxNo){
      return new Promise((resolve,reject)=>{
        // 请求列表检查设备是否已有定时策略
        listCron({boxNo}).then(response=>{
            // 如果返回的rows数组非空，说明设备已有定时策略
            resolve(!!response.rows.length);
        }).catch(error=>{
            // 请求失败时返回错误信息
            reject(error);
        });
      });
    },
    handleSubmitForStrategys(){
      if(this.selectedRows.length===0){this.$message.warning('请选择设备');return;}
      const idss=this.selectedRows.map(row=>row.id);
      console.log('idss:',idss);
      const provideTypes=this.selectedRows.map(row=>row.dsType);
      const selectedBoxNos=new Set(this.selectedRows.map(row=>row.dsId));
      const cronData = {
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        startTimeTwo: this.form.startTimeTwo,
        endTimeTwo: this.form.endTimeTwo,
        startTimeThree: this.form.startTimeThree,
        endTimeThree: this.form.endTimeThree,
        startTimeFour: this.form.startTimeFour,
        endTimeFour: this.form.endTimeFour,
        startTimeFive: this.form.startTimeFive,
        endTimeFive: this.form.endTimeFive,
        lightStatus: this.form.lightStatus,
        lightAdjustLevel: this.parseToNumber(this.form.lightAdjustLevel),
        lightStatusTwo: this.form.lightStatusTwo,
        lightAdjustLevelTwo: this.parseToNumber(this.form.lightAdjustLevelTwo),
        lightStatusThree: this.form.lightStatusThree,
        lightAdjustLevelThree: this.parseToNumber(this.form.lightAdjustLevelThree),
        lightStatusFour: this.form.lightStatusFour,
        lightAdjustLevelFour: this.parseToNumber(this.form.lightAdjustLevelFour),
        lightStatusFive: this.form.lightStatusFive,
        lightAdjustLevelFive: this.parseToNumber(this.form.lightAdjustLevelFive),
      };
      console.log('cronData:',cronData);
      const strategies=[
{start:cronData.startTime,end:cronData.endTime,lightStatus:cronData.lightStatus,lightAdjustLevel:cronData.lightAdjustLevel},
{start:cronData.startTimeTwo,end:cronData.endTimeTwo,lightStatusTwo:cronData.lightStatusTwo,lightAdjustLevelTwo:cronData.lightAdjustLevelTwo},
{start:cronData.startTimeThree,end:cronData.endTimeThree,lightStatusThree:cronData.lightStatusThree,lightAdjustLevelThree:cronData.lightAdjustLevelThree},
{start:cronData.startTimeFour,end:cronData.endTimeFour,lightStatusFour:cronData.lightStatusFour,lightAdjustFour:cronData.lightAdjustLevelFour},
{start:cronData.startTimeFive,end:cronData.endTimeFive,lightStatusFive:cronData.lightStatusFive,lightAdjustFive:cronData.lightAdjustLevelFive},];
      if(!strategies.some(strategy=>strategy.start&&strategy.end)){this.$message.warning('请至少填写一个定时策略');return;}
      const checkPromises = [...selectedBoxNos].map(dsId=>this.checkDeviceHasCron(dsId));
      Promise.all(checkPromises).then(results => {
          results.forEach((deviceExists, index) => {
            const id = [...idss][index];
            const boxNo = [...selectedBoxNos][index];
            const provideType = [...provideTypes][index];
            if(!deviceExists){//如果设备没有定时策略，则添加定时策略
              this.addDeviceAndCron(id, boxNo, provideType, cronData);
            }else{//如果设备已有定时策略，则更新定时策略
              this.updateCronFields(id, boxNo, provideType, cronData);
            }
          })
          if(results.some(result=>result)){this.$message.success('定时策略操作成功');}
      }).catch(error=>{this.$message.error('检查设备时出错:'+error.message);});
    },
    parseToNumber(value) {
      if(typeof value==='string'){return parseInt(value);}
      else if(typeof value==='number'){return value;}
      else {return value;}
    },
    addDeviceAndCron(id, boxNo, provideType, cronData) {
      addCron({id,boxNo,provideType,...cronData}).then(() => {
          this.cronBoxNoList.push(boxNo);
          this.cronList.push({ boxNo, ...cronData });
          this.$message.success('定时任务添加成功');
          this.dialogVisible = false;
          this.getList();}).catch(error => {
          if (error.code === 'DUPLICATE_BOXNO') {
            this.updateCronFields(id,boxNo,provideType,cronData);
          } else {
            this.$message.error('添加设备失败: ' + error.message);
          }
    });},
    updateCronFields(id,boxNo,provideType,cronData) {
      updateCron({id,boxNo,provideType,...cronData}).then(() => {
          const index = this.cronList.findIndex(item => item.boxNo === boxNo);
          if (index !== -1) {
            this.cronList[index] = { boxNo, ...cronData };
          }
          this.dialogVisible = false;
          this.getList();
        }).catch(error => {
          this.$message.error('更新定时策略失败: ' + error.message);
        });
    },
    openCronDialog() {
      this.form={startTime:'',endTime:'',startTimeTwo:'',endTimeTwo:'',startTimeThree:'',endTimeThree:'',startTimeFour:'',endTimeFour:'',startTimeFive:'',endTimeFive:'',lightStatus:'',lightAdjustLevel:'',lightStatusTwo:'',lightAdjustLevelTwo:'',lightStatusThree:'',lightAdjustLevelThree:'',lightStatusFour:'',lightAdjustLevelFour:'',lightStatusFive:'',lightAdjustLevelFive:''};
      this.dialogVisible = true;
    },
    openDialog() {
      // 如果没有选择设备，弹出提示
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择设备进行操作。');
        return;
      }
      if (this.selectedRows.length > 1) {
        this.openCronDialog();
        return;
      }
      const selectedBoxNo = this.selectedRows[0].dsId;
      this.checkDeviceHasCron(selectedBoxNo).then(exists => {
        if (exists) {
          this.$message.warning('已选择设备存在定时任务，请修改已有定时任务。');
        } else {
          this.openCronDialog();  // 设备没有定时任务，允许打开对话框
        }
      }).catch(error => {
        this.$message.error('检查设备时出错: ' + error.message);
      });
    },
    sendDialog() {
      this.reset();
      this.$refs.displayy.show(this.selectedRows);
    },
    updtVolume() {
      const volumeLvl = this.sldVolumeLvl;
      console.log('[volumeLvl]:', volumeLvl);
      this.hgdisplayList.forEach(row => {
        if (row.checked) {
          const snThing = {
            lightLevel: volumeLvl,
            type: 6,
            id: row.id,
            provideType: row.dsType,
            sno: row.dsId,
            productKey: "callCardService",
            fn: "setVolume"
          };
          this.publish(snThing).then(response => {
            this.$modal.msgSuccess("调音量成功");
            this.getList();
            this.sldVolumeLvl='';
          }).catch(error => {
            console.error('error', error);
            this.$modal.msgError("调音量失败");
          });
        }
      });
    },
    updtLevel() {
      const lightLvl = parseInt(this.sldLightLvl);
      console.log('[lightLvl]:', lightLvl);
      this.hgdisplayList.forEach(row => {
        if (row.checked) {
          const snThing = {
            lightLevel: lightLvl,
            type: 5,
            id: row.id,
            provideType: row.dsType,
            sno: row.dsId,
            productKey: "callCardService",
            fn: "setBrightness"
          };
          this.publish(snThing).then(response => {
            this.$modal.msgSuccess("调亮度成功");
            this.getList();
            this.sldLightLvl='';
          }).catch(error => {
            console.error('error', error);
            this.$modal.msgError("调亮度失败");
          });
        }
      });
    },
    handleTurnOn() {
      const selectedRows = this.selectedRows;
      if (selectedRows.length === 0) {this.$message.warning('请选择设备进行操作！');return;}
      const requests = selectedRows.map(row => {
        if (!row.dsId) {this.$message.error('选中的设备缺少设备编号！');return null;}
        return this.publish({
          arg: true,
          type: 3,
          id: row.id,
          provideType: row.dsType,
          sno: row.dsId,
          productKey: "callCardService",
          fn: "setScreenOpen"
        });
      }).filter(request => request !== null);
      Promise.all(requests).then(results => {
          let msgsuccess = "", msgfail = "", jsonArray = [];
          results.forEach(item=>{jsonArray.push(item.data);});
          const result = jsonArray.reduce((acc, obj) => {return { ...acc, ...obj };},{});
          for (const [key, value] of Object.entries(result)) {
              if(value){
                msgsuccess+=key+",";
              }else{
                msgfail+=key+",";
              }
          }
          const msgsuccrslt = msgsuccess.substring(0,msgsuccess.length-1);
          const msgfailrslt = msgfail.substring(0,msgfail.length-1);
          if(msgsuccess.length>0&&msgfail.length>0){this.$message.warning('开启成功的控制卡号：'+msgsuccrslt+' 开启失败的控制卡号：'+msgfailrslt,{duration:15000});}
          if(msgsuccess.length>0&&msgfail.length==0){this.$modal.msgSuccess('开启成功的控制卡号：'+msgsuccrslt,{duration:18000});}
          if(msgsuccess.length==0&&msgfail.length>0){this.$message.warning('开启失败的控制卡号：'+msgfailrslt,{duration:15000});}
          this.getList();
      }).catch(error => {console.error(error);});
    },
    handleTurnOff() {
      const selectedRows = this.selectedRows;
      if (selectedRows.length === 0) {this.$message.warning('请选择设备进行操作！');return;}
      const requests = selectedRows.map(row => {
        if (!row.dsId) {this.$message.error('选中的设备缺少设备编号！');return null;}
        return this.publish({
          arg: false,
          type: 4,
          id: row.id,
          provideType: row.dsType,
          sno: row.dsId,
          productKey: "callCardService",
          fn: "setScreenOpen"
        });
      }).filter(request => request !== null);
      Promise.all(requests).then(results => {
          let msgsuccess = "", msgfail = "", jsonArray = [];
          results.forEach(item=>{jsonArray.push(item.data);});
          const result = jsonArray.reduce((acc, obj) => {return { ...acc, ...obj };},{});
          for (const [key, value] of Object.entries(result)) {
              if(value){
                msgsuccess+=key+",";
              }else{
                msgfail+=key+",";
              }
          }
          const msgsuccrslt = msgsuccess.substring(0,msgsuccess.length-1);
          const msgfailrslt = msgfail.substring(0,msgfail.length-1);
          if(msgsuccess.length>0&&msgfail.length>0){this.$message.warning('关灯成功的控制卡号：'+msgsuccrslt+' 关灯失败的控制卡号：'+msgfailrslt,{duration:15000});}
          if(msgsuccess.length>0&&msgfail.length==0){this.$modal.msgSuccess('关灯成功的控制卡号：'+msgsuccrslt,{duration:18000});}
          if(msgsuccess.length==0&&msgfail.length>0){this.$message.warning('关灯失败的控制卡号：'+msgfailrslt,{duration:15000});}
          this.getList();
      }).catch(error => {console.error(error);});
    },
    publish(snThing) {
      console.log('2:', JSON.stringify(snThing));
      return request({
        url: '/mqtt/backclient/publishxixun',
        method: 'post',
        data: snThing,
        headers: {'Content-Type': 'application/json'}
      })
    },
    getStatusImage(status) {// 确保比较的是字符串类型
      return status==='1'?require('@/assets/bigScreen/img/dison.png'):require('@/assets/bigScreen/img/disoff.png');
    },
    getStateImags(status) {
      return status==='1'?require('@/assets/bigScreen/img/wifion.png'):require('@/assets/bigScreen/img/wifi.png');
    },
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        console.log(`Selected ID: ${selectedId}, nickName: ${selectedOption.nickName}`);
        this.form.customerId = selectedOption.userId;    // 将选择的 userId 存入 adminId 字段
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        console.log('Selected Project Name:', selectedOption.projectname);
        this.form.projectId = selectedOption.id;
      } else {console.error('No matching data found for value:', value);}
    },
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList=response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
          console.log("options", this.options);
        }
      } catch (error) {console.error('error', error);}
    },
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList=response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
          console.log("projectnameOptions", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    /** 查询慧光智慧显示屏列表 */
    getList() {
      this.loading = true;
      listHgdisplay(this.queryParams).then(response => {
        this.hgdisplayList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nickName: null,
        adminId: null,
        customerId: null,
        dsType: null,
        dsId: null,
        dsStatus: "0",
        boxNo: null,
        lightName: null,
        projectId: null,
        lng: null,
        lat: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        remark: null,
        deleteBy: null,
        updateTime: null,
        deleteTime: null,
        dsAdjustLevel: null,
        dsError: null,
        signalt: null,
        mlux: null,
        soundDecibelValue: null,
        pm10: null,
        pm25: null,
        humidity: null,
        temperature: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selectedRows = selection;
      this.hgdisplayList.forEach(row => {
        row.checked = selection.some(item => item.id === row.id);
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHgdisplay(id).then(response => {
        this.form = response.data;
        console.log("response", response.data);
        this.open = true;
        this.ssss = this.form.dsId;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHgdisplay(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess("修改成功");
              }
              this.open = false;
              this.getList();
              this.fetchCronBoxNoList();
            }).catch(error => {
              console.error("error", error);
              this.$modal.msgError("修改失败");});
          } else {
            addHgdisplay(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess("新增成功");
              }
              this.open = false;
              this.getList();
            });
          }
          let b;
          listCron({ boxNo: this.ssss }).then(response => {// 检查 response.rows 是否存在并且不是空数组
              if (response.rows && response.rows.length > 0) {
                b = response.rows[0].id;
                const cronData = {id:b,boxNo:this.form.dsId};
                updateCronBoxNo(cronData).then(response => {// 更新成功
                }).catch(error => {
                  console.error("error", error);
                  this.$modal.msgError("定时任务更新失败");});}
            }).catch(error => {
              this.$modal.msgError("获取定时任务列表失败");
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除显示屏编号为"' + ids + '"的数据项？').then(function() {
        return delHgdisplay(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/hgdisplay/export', {
        ...this.queryParams
      }, `hgdisplay_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.hover-operate-table {
  position: relative;
  .el-table__body-wrapper {
    overflow-x: auto !important;
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f5f5f5;
    &::-webkit-scrollbar {
      height: 8px;
      background-color: #f5f5f5;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #c1c1c1;
      border-radius: 4px;
    }
  }
}
.el-table .operate-column {
  position: sticky;
  right: 0;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none;
  background-color: #fff;
  z-index: 2; /* 确保在滚动时显示在其他内容上方 */
}
.el-table .operate-column.show {
  opacity: 1;
  pointer-events: auto;
}
.el-table .operate-column .cell {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1); /* 添加阴影增强视觉效果 */
}
.el-table__body tr td {
  position: relative;
}
.custom-select .el-input__inner {
  border-color: #093077; /* 设置边框颜色为蓝色 */
  border-style: solid; /* 确保边框是实线 */
}
.custom-select {
  width: 20%;
  margin-top: 10px;
  margin-left: 60px;
}
.move-select {
  position: relative;
  top: -24px;
}
</style>
